package org.example.webserver.controller;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.annotation.Pointcut;
import org.example.webserver.pojo.User;
import org.example.webserver.service.UserService;
import org.example.webserver.utils.Result;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    @PostMapping("/login")
    public Result<User> login(@RequestParam String user,@RequestParam String password,HttpServletRequest request){
        User user_0= userService.loginService(user,password);
        if(user_0!=null){
            saveUserToSession(user_0,request);
            return Result.success(user_0,"登录成功");
        }else{
            return Result.error("001","用户名或密码错误");
        }
    }

    @PostMapping("/register")
    public Result<User> register(@RequestBody User user,HttpServletRequest request){
        user.setUser_group("user");
        User user_0=userService.registService(user);
        if(user_0!=null){
            saveUserToSession(user_0,request);
            return Result.success(user_0,"注册成功");
        }else{
            return Result.error("002","用户名已存在");
        }
    }

    @PostMapping("/getUser")
    public Result<User> getUser(HttpServletRequest request){
        User user= (User) request.getSession().getAttribute("user");
        if(user!=null){
            return Result.success(user);
        }else{
            return Result.error("003","空User");
        }
    }

    @PostMapping("/userExit")
    public Result<User> userExit(HttpServletRequest request){
        request.getSession().removeAttribute("user");
        return Result.success();
    }

    @PostMapping("/toBeMerchant")
    public Result<User> toBeMerchant(HttpServletRequest request){
        User user=userService.toBeMerchant((User) request.getSession().getAttribute("user"));
        request.getSession().setAttribute("user",user);
        return Result.success(user);
    }

    public void saveUserToSession(User user, HttpServletRequest request){
        request.getSession().setAttribute("user",user);
    }
}
